package cn.kailangtu.serialutils.api;

import android.util.Log;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

import cn.kailangtu.commontools.CommonUtils;

public class DataAnalysis {
    static String HEARD = "7B7B";
    static String END = "7D7D";
    static int CMD_MIN_LENGTH = 16;
    static int CMD_LENGTHDATA_START_INDEX = 6;
    static int CMD_LENGTH_LENGTH = 4;
    public static List<String> GetCmd(String source){
        /*
        1,找7B7B,找不到，整条指令扔掉
        2，得到长度，校验长度：
            如果长度算出的结尾位置正确，算一条指令
            如果长度算出的结尾位置不正常，找下一个7B7B，如果没有，全扔掉。如果找到重复上一步的判断
        3，获取一条完整指令后，看后面是否有其他指令，有就把后面的截出来，返回上面1的步骤，继续判断
         */

        List<String> result = new ArrayList<>();
        source = source.toUpperCase();
        while(source.length() >= CMD_MIN_LENGTH)
        {
            int position7B7B = source.indexOf(HEARD);
            if(position7B7B > -1)
            {
                int positionLength = position7B7B + CMD_LENGTHDATA_START_INDEX;
                int length  = new BigInteger( source.substring(positionLength,positionLength+ CMD_LENGTH_LENGTH), 16).intValue();
                int positionEnd = length * 2 + CMD_MIN_LENGTH - END.length() + position7B7B;
                int positionComplete = positionEnd + END.length();
                if(source.length() >= positionComplete) {
                    String currentEnd = source.substring(positionEnd, positionComplete);
                    if (currentEnd.equals(END)) {
                        String foundCmd = source.substring(position7B7B, positionComplete);
                       // Log.d("AAAAAAAAAAA", foundCmd);
                        if (CommonUtils.check(foundCmd)) {
                            result.add(foundCmd);
                        }
                        if (source.length() > positionComplete) {
                            source = source.substring(positionComplete);
                        } else {
                            source = "";
                        }
                    } else {
                        source = "";
                    }
                }
                else
                {
                    source = "";
                }
            }else {
                source = "";
            }
        }
        return result;
    }
}
